package com.letv.core.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.letv.core.bean.AlbumNew;
import com.letv.core.bean.FavouriteBean;
import com.letv.core.bean.FavouriteBeanList;
import com.letv.core.constant.DatabaseConstant;
import com.letv.core.utils.LetvTools;
import com.letv.core.utils.LogInfo;

import java.util.HashSet;
import java.util.Iterator;

public class FavoriteTraceHandler {

	private Context context;
	
	public FavoriteTraceHandler(Context context) {
		this.context = context;
	}



	/**
	 * 根据 ID 更新数据表
	 */
	private boolean updateById(FavouriteBean mFavBean , long timeStamp) {
		try {
			if (mFavBean != null) {
				ContentValues contentValues = new ContentValues();
				contentValues.put(DatabaseConstant.FavoriteRecord.Field.TIMESTAMP , timeStamp);

				contentValues.put(DatabaseConstant.FavoriteRecord.Field.ID , mFavBean.id);
				contentValues.put(DatabaseConstant.FavoriteRecord.Field.TITLE , mFavBean.nameCn);
				contentValues.put(DatabaseConstant.FavoriteRecord.Field.SUBTITLE , mFavBean.subTitle);
				contentValues.put(DatabaseConstant.FavoriteRecord.Field.ICON , mFavBean.pic);
				contentValues.put(DatabaseConstant.FavoriteRecord.Field.COUNT , mFavBean.nowEpisodes);
				contentValues.put(DatabaseConstant.FavoriteRecord.Field.EPISODE , mFavBean.episode);
				contentValues.put(DatabaseConstant.FavoriteRecord.Field.TYPE , mFavBean.type);
				contentValues.put(DatabaseConstant.FavoriteRecord.Field.ISEND , mFavBean.isEnd);

				context.getContentResolver().update(LetvContentProvider.URI_FAVORITETRACE, contentValues,
						DatabaseConstant.FavoriteRecord.Field.ID+"=?",
						new String[] { mFavBean.id + "" });
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean saveFavoriteTrace(FavouriteBean mFavBean , long timeStamp){
		try {

			LogInfo.log("Emerson", "-------收藏 key = "+ mFavBean.id
					+ "，----是否是以收藏 -》"+ hasFavoriteTrace(mFavBean.id));
			if(hasFavoriteTrace(mFavBean.id)){
				return updateById(mFavBean, timeStamp);
			}
			ContentValues contentValues = new ContentValues();
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.TIMESTAMP , timeStamp);

			contentValues.put(DatabaseConstant.FavoriteRecord.Field.ID , mFavBean.id);
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.TITLE , mFavBean.nameCn);
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.SUBTITLE , mFavBean.subTitle);
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.ICON , mFavBean.pic);
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.COUNT , mFavBean.nowEpisodes);
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.EPISODE , mFavBean.episode);
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.TYPE , mFavBean.type);
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.ISEND , mFavBean.isEnd);
			//wangxuefang 增加channelId的数据库存储
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.CID , mFavBean.channelId);
			context.getContentResolver().insert(LetvContentProvider.URI_FAVORITETRACE, contentValues);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
//正片收藏
//	private boolean updateById(RecAlbumInfo tabAluAlbumInfoBean, long timeStamp){
//		try {
//			if (tabAluAlbumInfoBean != null) {
//				ContentValues contentValues = new ContentValues();
//				contentValues.put(DatabaseConstant.FavoriteRecord.Field.TIMESTAMP , timeStamp);
//
//				contentValues.put(DatabaseConstant.FavoriteRecord.Field.TITLE , tabAluAlbumInfoBean.nameCn);
//				contentValues.put(DatabaseConstant.FavoriteRecord.Field.SUBTITLE , tabAluAlbumInfoBean.subTitle);
//				contentValues.put(DatabaseConstant.FavoriteRecord.Field.ICON , tabAluAlbumInfoBean.pic320);
//				contentValues.put(DatabaseConstant.FavoriteRecord.Field.COUNT , tabAluAlbumInfoBean.nowEpisodes);
//				contentValues.put(DatabaseConstant.FavoriteRecord.Field.EPISODE , tabAluAlbumInfoBean.episode);
//				contentValues.put(DatabaseConstant.FavoriteRecord.Field.TYPE , tabAluAlbumInfoBean.type);
//				contentValues.put(DatabaseConstant.FavoriteRecord.Field.ISEND , tabAluAlbumInfoBean.isEnd);
//				context.getContentResolver().delete(LetvContentProvider.URI_FAVORITETRACE,
//						DatabaseConstant.FavoriteRecord.Field.ID+"=?" ,
//						new String[] {tabAluAlbumInfoBean.pid+""});
//				context.getContentResolver().insert(LetvContentProvider.URI_FAVORITETRACE, contentValues);
////                context.getContentResolver().update(LetvContentProvider.URI_FAVORITETRACE, contentValues,
////                        DatabaseConstant.FavoriteRecord.Field.ID+"=?",
////                        new String[] { mFavBean.id + "" });
//				return true;
//			} else {
//				return false;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			return false;
//		}
//	}
//
//	public boolean saveFavoriteTrace(RecAlbumInfo tabAluAlbumInfoBean, long timeStamp){
//		try {
//			if (hasFavoriteTrace(Long.parseLong(tabAluAlbumInfoBean.pid))) {
//				return updateById(tabAluAlbumInfoBean, timeStamp);
//			}
//
//			ContentValues contentValues = new ContentValues();
//			contentValues.put(
//					DatabaseConstant.FavoriteRecord.Field.TIMESTAMP,
//					timeStamp);
//
//			contentValues.put(DatabaseConstant.FavoriteRecord.Field.ID,
//					tabAluAlbumInfoBean.pid);
//			contentValues.put(DatabaseConstant.FavoriteRecord.Field.TITLE,
//					tabAluAlbumInfoBean.nameCn);
//			contentValues.put(
//					DatabaseConstant.FavoriteRecord.Field.SUBTITLE,
//					tabAluAlbumInfoBean.subTitle);
//			contentValues.put(DatabaseConstant.FavoriteRecord.Field.ICON,
//					tabAluAlbumInfoBean.pic320);
//			contentValues.put(DatabaseConstant.FavoriteRecord.Field.COUNT,
//					tabAluAlbumInfoBean.nowEpisodes);
//			contentValues.put(
//					DatabaseConstant.FavoriteRecord.Field.EPISODE,
//					tabAluAlbumInfoBean.episode);
//			contentValues.put(DatabaseConstant.FavoriteRecord.Field.TYPE,
//					tabAluAlbumInfoBean.type);
//			contentValues.put(DatabaseConstant.FavoriteRecord.Field.ISEND,
//					tabAluAlbumInfoBean.isEnd);
//			// wangxuefang 增加channelId的数据库存储
//			contentValues.put(DatabaseConstant.FavoriteRecord.Field.CID,
//					tabAluAlbumInfoBean.cid);
//			context.getContentResolver().insert(
//					LetvContentProvider.URI_FAVORITETRACE, contentValues);
//			return true;
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//
//		return false;
//	}

	public boolean saveFavoriteTrace(AlbumNew tabAluAlbumInfoBean, long timeStamp){
		try {
			if (hasFavoriteTrace(tabAluAlbumInfoBean.getId())) {
			    LogInfo.log("Emerson", "------- 里面有 id 更新数据 id = " +tabAluAlbumInfoBean.getId());
				return updateById(tabAluAlbumInfoBean, timeStamp);
			}
			LogInfo.log("Emerson", "------- 添加　数据 id = " +tabAluAlbumInfoBean.getId());
			ContentValues contentValues = new ContentValues();
			contentValues.put(
					DatabaseConstant.FavoriteRecord.Field.TIMESTAMP,
					timeStamp);

			contentValues.put(DatabaseConstant.FavoriteRecord.Field.ID,
					tabAluAlbumInfoBean.getId());
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.TITLE,
					tabAluAlbumInfoBean.getNameCn());
			contentValues.put(
					DatabaseConstant.FavoriteRecord.Field.SUBTITLE,
					tabAluAlbumInfoBean.getSubTitle());
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.ICON,
					tabAluAlbumInfoBean.getPic320_200());
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.COUNT,
					tabAluAlbumInfoBean.getNowEpisodes());
			contentValues.put(
					DatabaseConstant.FavoriteRecord.Field.EPISODE,
					tabAluAlbumInfoBean.getEpisode());
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.TYPE,
					tabAluAlbumInfoBean.getType());
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.ISEND,
					tabAluAlbumInfoBean.getIsEnd());
			// wangxuefang 增加channelId的数据库存储
			contentValues.put(DatabaseConstant.FavoriteRecord.Field.CID,
					tabAluAlbumInfoBean.getCid());
			context.getContentResolver().insert(
					LetvContentProvider.URI_FAVORITETRACE, contentValues);
			return true;
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return false;
	}

    private boolean updateById(AlbumNew tabAlbumInfoBean, long timeStamp){
    	try {
            if (tabAlbumInfoBean != null) {
                ContentValues contentValues = new ContentValues();
                contentValues.put(DatabaseConstant.FavoriteRecord.Field.TIMESTAMP , timeStamp);

                contentValues.put(DatabaseConstant.FavoriteRecord.Field.TITLE , tabAlbumInfoBean.getNameCn());
                contentValues.put(DatabaseConstant.FavoriteRecord.Field.SUBTITLE , tabAlbumInfoBean.getSubTitle());
//                contentValues.put(DatabaseConstant.FavoriteRecord.Field.ICON , tabAlbumInfoBean.getPic320_200());
                contentValues.put(DatabaseConstant.FavoriteRecord.Field.COUNT , tabAlbumInfoBean.getNowEpisodes());
                contentValues.put(DatabaseConstant.FavoriteRecord.Field.EPISODE , tabAlbumInfoBean.getEpisode());
                contentValues.put(DatabaseConstant.FavoriteRecord.Field.TYPE , tabAlbumInfoBean.getType());
                contentValues.put(DatabaseConstant.FavoriteRecord.Field.ISEND , tabAlbumInfoBean.getIsEnd());
                context.getContentResolver().delete(LetvContentProvider.URI_FAVORITETRACE,
                		DatabaseConstant.FavoriteRecord.Field.ID+"=?" ,
                		new String[] {tabAlbumInfoBean.getId()+""});
                context.getContentResolver().insert(LetvContentProvider.URI_FAVORITETRACE,contentValues);
//                context.getContentResolver().update(LetvContentProvider.URI_FAVORITETRACE, contentValues,
//                        new String(DatabaseConstant.FavoriteRecord.Field.ID+"=?"),
//                        new String[] { tabAlbumInfoBean.getId() + "" });
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
	/**
	 * 得到所有的收藏记录
	 * */
	public FavouriteBeanList getAllFavoriteTrace(){
		Cursor cursor = null ;
		FavouriteBeanList list = null ;
		try{
			cursor = context.getContentResolver().query(LetvContentProvider.URI_FAVORITETRACE, null, null, null, DatabaseConstant.FavoriteRecord.Field.TIMESTAMP + " desc");
			list = new FavouriteBeanList();
			int count = 0;
			while(cursor.moveToNext()){
				FavouriteBean mFavouriteBean = new FavouriteBean() ;
				mFavouriteBean.id = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.ID));
				mFavouriteBean.channelId = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.CID));
				mFavouriteBean.nowEpisodes = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.COUNT));
				mFavouriteBean.episode = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.EPISODE));
				mFavouriteBean.isEnd = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.ISEND));
				mFavouriteBean.nameCn = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.TITLE));
				mFavouriteBean.pic = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.ICON));
				mFavouriteBean.subTitle = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.SUBTITLE));
				mFavouriteBean.type = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.TYPE));
				list.add(mFavouriteBean);
				count++;
			}
			list.setMax(count);
		}catch(Exception e){
		    e.toString();
		}finally{
			LetvTools.closeCursor(cursor);
		}
		return list ;
	}
	
	/**
	 * 得到所有的收藏记录
	 * Added by chenhong on 2014/07/31
	 * */
	public FavouriteBeanList getLatestThreeFavoriteTrace(){
		Cursor cursor = null ;
		FavouriteBeanList list = null ;
		try{
			cursor = context.getContentResolver().query(LetvContentProvider.URI_FAVORITETRACE, null, null, null, DatabaseConstant.FavoriteRecord.Field.TIMESTAMP + " desc");
			list = new FavouriteBeanList();
			int count = 0;
			while(cursor.moveToNext() && count < 3){
				FavouriteBean mFavouriteBean = new FavouriteBean() ;
//				mFavouriteBean.id = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.ID));
//				mFavouriteBean.channelId = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.CID));
//				mFavouriteBean.nowEpisodes = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.COUNT));
//				mFavouriteBean.episode = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.EPISODE));
//				mFavouriteBean.isEnd = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.ISEND));
				mFavouriteBean.nameCn = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.TITLE));
//				mFavouriteBean.pic = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.ICON));
//				mFavouriteBean.subTitle = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.SUBTITLE));
//				mFavouriteBean.type = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstant.FavoriteRecord.Field.TYPE));
				list.add(mFavouriteBean);
				count++;
			}
		}finally{
			LetvTools.closeCursor(cursor);
		}
		return list ;
	}
	
	/**
	 * 删除全部收藏记录
	 * */
	public void clearAll(){
		context.getContentResolver().delete(LetvContentProvider.URI_FAVORITETRACE, null, null);
	}
	
	/**
	 * 删除一条记录
	 * */
	public boolean remove(long id){
		try {
			context.getContentResolver().delete(LetvContentProvider.URI_FAVORITETRACE, DatabaseConstant.FavoriteRecord.Field.ID+"=?" , new String[] {id+""});
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 删除多条记录
	 * */
	public void remove(HashSet<FavouriteBean> set){
		Iterator<FavouriteBean> i = set.iterator() ;
		long id = 0;
		while (i.hasNext()) {
			id =  i.next().id;
			remove(id);
		}
	}
	
	/**
	 * 判断是否记录已存在
	 * */
	public boolean hasFavoriteTrace(long id){
		Cursor cursor = null ;
		try{
			cursor = context.getContentResolver().query(LetvContentProvider.URI_FAVORITETRACE, null, DatabaseConstant.FavoriteRecord.Field.ID+"=?" , new String[] {id+""}, null);
			int count = cursor.getCount();
			return (count > 0);
		}finally{
			LetvTools.closeCursor(cursor);
		}
	}
}
